package com.hsd.core.tags.helper;

import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;

/**
 * OPTION标签
 * 
 * @author Abdi
 * @description
 * @created Oct 25, 2013 3:48:53 PM
 */
@SuppressWarnings("unchecked")
public class OptionWriter {
	private List<Map> optionSource;
	private String selectedValue;
	private Boolean hideEmpty;

	/**
	 * 构造器
	 * 
	 * @param optionSource
	 * @param selectedValue
	 * @param showEmpty
	 */
	public OptionWriter(List<Map> optionSource, String selectedValue,
			Boolean hideEmpty) {
		this.optionSource = optionSource;
		this.selectedValue = selectedValue;
		this.hideEmpty = hideEmpty;
	}

	/**
	 * 输出Option标签集合
	 * 
	 * @param tagWriter
	 * @throws JspException
	 */
	public void writeOptions(TagWriter tagWriter) throws JspException {
		if (!this.hideEmpty && null != optionSource && optionSource.size() > 0) {
			renderOption(tagWriter, "", "", false);
		}
		if(null != this.optionSource){
			for (Map codeData : this.optionSource) {
				String value = String.valueOf(codeData.get("codevalue"));
				String label = String.valueOf(codeData.get("codename"));
				boolean selected = false;
				if (value.equals(this.selectedValue)) {
					selected = true;
				}
				renderOption(tagWriter, value, label, selected);
			}
		}
	}

	/**
	 * 输出单个Option标签
	 * 
	 * @param tagWriter
	 * @param value
	 * @param label
	 * @param selected
	 * @throws JspException
	 */
	private void renderOption(TagWriter tagWriter, String value, String label,
			Boolean selected) throws JspException {
		tagWriter.startTag("option");
		tagWriter.writeAttribute("value", value);
		if (selected) {
			tagWriter.writeAttribute("selected", "selected");
		}
		tagWriter.appendValue(label);
		tagWriter.endTag();
	}

	public List<Map> getOptionSource() {
		return optionSource;
	}

	public void setOptionSource(List<Map> optionSource) {
		this.optionSource = optionSource;
	}

	public String getSelectedValue() {
		return selectedValue;
	}

	public void setSelectedValue(String selectedValue) {
		this.selectedValue = selectedValue;
	}

	public Boolean getHideEmpty() {
		return hideEmpty;
	}

	public void setHideEmpty(Boolean hideEmpty) {
		this.hideEmpty = hideEmpty;
	}
}
